import 'package:flutter/material.dart';
import 'package:shining_red_star/definitions/router.dart';
import 'package:shining_red_star/model/some_thing.dart';
import '../../api/list_some_thing.dart';
import '../../model/router_params.dart';
import '../../widgets/auto_grid.dart';
import '../../widgets/some_thing_index_card.dart';
import '../../wrappers/safe-area.dart';

class SomeThingIndexPage extends StatefulWidget {
  const SomeThingIndexPage({super.key});

  @override
  State<SomeThingIndexPage> createState() => _SomeThingIndexPageState();
}

class _SomeThingIndexPageState extends State<SomeThingIndexPage> {
  List<SomeThingInfo> someThingList = [];

  void loadData() {
    listSomeThing().then((res) {
      setState(() {
        someThingList = res;
      });
    });
  }

  void nav({String? group, String? id}) {
    Navigator.pushNamed(context, RouterKey.someThingDetail.value,
        arguments: CommonDetailRouterArguments(
          group: group,
          id: id,
        ));
  }

  @override
  void initState() {
    super.initState();
    loadData();
  }

  @override
  Widget build(BuildContext context) {
    int i = 0;
    return SafeAreaPageWrapper(
      padding: EdgeInsets.all(12),
      child: someThingList.isEmpty
          ? Center(
              child: Text('数据加载中'),
            )
          : AutoGrid(
              expectItemWidth: 96,
              expectItemHeight: 118,
              calcHeight: (itemWidth) {
                return itemWidth + 28;
              },
              mainAxisSpacing: 12,
              crossAxisSpacing: 12,
              keepProportion: true,
              children: someThingList.map((item) {
                return SomeThingIndexCard(
                  autofocus: i++ == 0,
                  someThing: item,
                  onConfirm: () {
                    nav(id: item.id);
                  },
                );
              }).toList(),
            ),
    );
  }
}
